<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * listship controller
 * @author Phuc Nguyen - 09/03/2015
 * http://www.facebook.com/phucthuong
 * email : nguyenvanphuc0626@gmail.com
*/
class Listship extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('listship');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('listship_model');
			$this->set_controller('listship');
			$this->set_model($this->listship_model);
		}
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }
        
        public function index(){
            $this->menuTop();
            $this->view_data['lists']    =   $this->listship_model->getListShip();

            $this->load->view('auth/listship/index', $this->view_data);
        }
        
        public function load(){
            $this->load->view('auth/listship/load', $this->view_data);
        }
        
        public function assign(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->view_data['phone']           =   $this->input->get('phone');
                $this->view_data['salesID']         =   $this->input->get('salesID');
                $this->load->view('auth/listship/assign', $this->view_data);
                
            }
            
        }
        public function assign_post(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $result =   $this->listship_model->find_by(array('saleID'=>$this->input->post('salesID'),'phone'=>$this->input->post('phone')));
                
                $this->view_data["assign"]                                  = new stdClass();
                $this->view_data["assign"]->saleID                          = $this->input->post('salesID');
                $this->view_data["assign"]->phone                           = $this->input->post('phone');
                $this->view_data["assign"]->booker                          = $this->input->post('booker');
                $this->view_data["assign"]->owner                           = $this->session->userdata['user_id'];
                $this->view_data["assign"]->agent_code                      = $this->session->userdata['agent_code'];
                $this->view_data["assign"]->lastupdated                     = date("Y-m-d H:i:s",time());
                
                if(empty($result)){    
                    $id = $this->listship_model->create($this->view_data["assign"]);
                } else {
                    $this->listship_model->update($this->view_data["assign"],$result[0]->id);
                    $id = true;
                }
                
                if($id){
                    //admin log
                    $paramAdminLog  = array(
                        'userid'            => $this->session->userdata['user_id'],
                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                        'ip'                => $_SERVER['REMOTE_ADDR'],
                        'logAction'         => '[listship] Assign for booker id='.$this->input->post('booker').' '.$this->lang->line('success'),
                        'agent_code'        => $this->session->userdata['agent_code']
                    );
                    $this->user_model->insertUserAdminLog($paramAdminLog);
                    die("0");
                } else {
                    $paramAdminLog  = array(
                        'userid'            => $this->session->userdata['user_id'],
                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                        'ip'                => $_SERVER['REMOTE_ADDR'],
                        'logAction'         => '[listship] Assign for booker id='.$this->input->post('booker').' '.$this->lang->line('fail'),
                        'agent_code'        => $this->session->userdata['agent_code']
                    );
                    $this->user_model->insertUserAdminLog($paramAdminLog);
                    die("1");
                }
            }
            
        }
        
        public function call(){
            $this->view_data['phone']           =   $this->input->get('phone');
            $this->view_data['salesID']         =   $this->input->get('salesID');
            $this->view_data['lists']           =   $this->listship_model->getListShip(array('phone'=>$this->view_data['phone'],'id'=>$this->view_data['salesID']));
            $this->load->view('auth/listship/call', $this->view_data);
        }
        
        public function call_post(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $result =   $this->listship_model->find_by(array('saleID'=>$this->input->post('salesID'),'phone'=>$this->input->post('phone')));
                
                $this->view_data["assign"]                                  = new stdClass();
                $this->view_data["assign"]->saleID                          = $this->input->post('salesID');
                $this->view_data["assign"]->phone                           = $this->input->post('phone');
                $this->view_data["assign"]->phone_callstatus                = $this->input->post('phone_callstatus');
                $this->view_data["assign"]->owner                           = $this->session->userdata['user_id'];
                $this->view_data["assign"]->agent_code                      = $this->session->userdata['agent_code'];
                $this->view_data["assign"]->lastupdated                     = date("Y-m-d H:i:s",time());
                
                $xml = simplexml_load_file(VOICE_IP_API.$this->input->post('phone'));
                $arr = $this->toArray($xml->user);
                $this->view_data["assign"]->phone_calltime                  = ($arr['Thoigiangoi'])?$arr['Thoigiangoi']:'0';
                
                if(empty($result)){    
                    $id = $this->listship_model->create($this->view_data["assign"]);
                } else {
                    $this->listship_model->update($this->view_data["assign"],$result[0]->id);
                    $id = true;
                }
                
                if($id){
                    //admin log
                    $paramAdminLog  = array(
                        'userid'            => $this->session->userdata['user_id'],
                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                        'ip'                => $_SERVER['REMOTE_ADDR'],
                        'logAction'         => '[listship] Saler gọi lại cho KH phone='.$this->input->post('phone').'-'.$this->lang->line('success'),
                        'agent_code'        => $this->session->userdata['agent_code']
                    );
                    $this->user_model->insertUserAdminLog($paramAdminLog);
                    die("0");
                } else {
                    $paramAdminLog  = array(
                        'userid'            => $this->session->userdata['user_id'],
                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                        'ip'                => $_SERVER['REMOTE_ADDR'],
                        'logAction'         => '[listship] Saler gọi lại cho KH phone='.$this->input->post('phone').'-'.$this->lang->line('fail'),
                        'agent_code'        => $this->session->userdata['agent_code']
                    );
                    $this->user_model->insertUserAdminLog($paramAdminLog);
                    die("1");
                }
                
            }
        }
        
        function toArray(SimpleXMLElement $xml) {
            $array = (array)$xml;

            foreach ( array_slice($array, 0) as $key => $value ) {
                if ( $value instanceof SimpleXMLElement ) {
                    $array[$key] = empty($value) ? NULL : toArray($value);
                }
            }
            return $array;
        }
        
        public function export(){
            if(isset($_POST['submit']) && $_POST['submit'] == 'export'){
               $beginTime                      = ($_POST['beginTime'])?strtotime($_POST['beginTime']):'';
               $endTime                        = ($_POST['endTime'])?strtotime($_POST['endTime']):'';
               
               if($beginTime == "" && $endTime == ""){
                    die(" Vui lòng điền ít nhất 1 thông tin!");
                }

                $result                         =   $this->listship_model->export(array('beginTime'=>$beginTime,'endTime'=>$endTime));
               
                $lsit = array();
                foreach($result as $key => $vals){
                    $booker     =   $this->user_model->find_by(array('id'=>$vals->booker),'firstname');
                    $lists[$key]     =   array(
                        'name'              =>          ($vals->name)?$vals->name:'',
                        'phone'             =>          ($vals->phone)?$vals->phone:'',
                        'note_customers'    =>          ($vals->note_customers)?$vals->note_customers:'',
                        'booker'            =>          $booker[0]->firstname,
                        'lastupdated'       =>          date("d-m-Y",$vals->lastupdated)
                    );
                }
                
                $this->view_data['lists']       =   $lists;
                $this->load->view('auth/listship/export', $this->view_data);
            }
        }
}